package com.xu.mb3;

import com.xu.mb3.mapper.UserAmountInfoMapper;
import com.xu.mb3.mapper.UserInfoMapper;
import com.xu.mybatis.entity.UserAmountInfo;
import com.xu.mybatis.entity.UserInfo;
import com.xu.mybatis.exception.MblException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author xuguan
 * @since 2024/11/10
 */
@Slf4j
public class MybatisSample {

    public static void sqlSession() {
        final SqlSession sqlSession = MbUtil.openSqlSession(false);
        final UserInfo userInfo = sqlSession.selectOne("com.xu.mb3.mapper.UserInfoMapper.selectById", 1L);
        log.info("userInfo={}", userInfo);
        final UserAmountInfo userAmountInfo = sqlSession.selectOne("com.xu.mb3.mapper.UserAmountInfoMapper.selectById", 1L);
        log.info("userAmountInfo={}", userAmountInfo);
        MbUtil.close(sqlSession);
    }

    public static void selectById() {
        final SqlSession sqlSession = MbUtil.openSqlSession(false);
        final UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
        final UserInfo userInfo = userInfoMapper.selectById(1L);
        log.info("userInfo={}", userInfo);
        MbUtil.close(sqlSession);
    }

    public static void transactional() {
        final SqlSession sqlSession = MbUtil.openSqlSession(false);

        try {
            final UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
            final UserAmountInfoMapper userAmountInfoMapper = sqlSession.getMapper(UserAmountInfoMapper.class);
            final UserInfo updateUserInfo = new UserInfo();
            updateUserInfo.setId(1L);
            updateUserInfo.setAge("18");
            updateUserInfo.setUpdateTime(LocalDateTime.now());
            final int updateUserInfoCnt = userInfoMapper.updateById(updateUserInfo);
            log.info("updateUserInfoCnt={}", updateUserInfoCnt);

            final UserAmountInfo updateUserAmountInfo = new UserAmountInfo();
            updateUserAmountInfo.setId(1L);
            updateUserAmountInfo.setAmount(new BigDecimal("1000000.00"));
            updateUserAmountInfo.setUpdateTime(LocalDateTime.now());
            final int updateUserAmountInfoCnt = userAmountInfoMapper.updateById(updateUserAmountInfo);
            log.info("updateUserAmountInfoCnt={}", updateUserAmountInfoCnt);

            sqlSession.commit();
        } catch (Exception e) {
            log.error("事务执行失败", e);
            throw new MblException(e);
        } finally {
            MbUtil.close(sqlSession);
        }
    }

    public static void main(String[] args) {
        sqlSession();
        // selectById();
        // transactional();
        // selectById();
    }
}
